package com.chuantou.yuba.ui.fragment;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;

import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.baidu.location.BDLocation;
import com.chuantou.yuba.R;
import com.chuantou.yuba.YBApp;
import com.chuantou.yuba.api.RequestManager;
import com.chuantou.yuba.api.UriHelper;
import com.chuantou.yuba.api.to.WeatherTO;
import com.chuantou.yuba.dao.CacheDao;
import com.chuantou.yuba.pojo.Cache;
import com.chuantou.yuba.ui.widget.WeatherPopup;
import com.chuantou.yuba.util.LoadCacheTask;

/**
 * 主界面fragment
 * 
 * @author dl1001
 * 
 */
public class HomeFragment extends BaseFragment implements OnClickListener {
	private static final String CACHE_KEY_WEATHER = "YUBA_WEATHER";
	private View mContentView;
	private ImageView mWeatherView;
	private WeatherPopup mPopup;
	private WeatherTO mWeatherTO;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		YBApp.get().startLocate(null);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		if (mContentView == null) {
			mContentView = inflater.inflate(R.layout.fg_main, null);
			mWeatherView = (ImageView) mContentView.findViewById(R.id.weather);
			mWeatherView.setOnClickListener(this);
			new WeatherCacheLoader(mContext, CACHE_KEY_WEATHER, WeatherTO.class).execute();
		}
		FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
		String tag = NewsListFragment.class.getName();
		Fragment fragment = getChildFragmentManager().findFragmentByTag(tag);
		if (fragment == null) {
			fragment = new NewsListFragment();
			transaction.add(R.id.fg_content, fragment, tag);
		} else {
			transaction.show(fragment);
		}
		transaction.commitAllowingStateLoss();
		ViewGroup parentView = (ViewGroup) mContentView.getParent();
		if (parentView != null) {
			parentView.removeView(mContentView);
		}
		YBApp.get().startLocate(null);
		return mContentView;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.weather:
			if (mPopup == null) {
				mPopup = new WeatherPopup(getActivity());
			}
			mPopup.setWeather(mWeatherTO);
			mPopup.showAsDropDown(mWeatherView, 0, -v.getWidth() / 4);
			break;
		default:
			break;
		}
	}

	/**
	 * 加载天气缓存
	 * 
	 * @author dl1001
	 * 
	 */
	class WeatherCacheLoader extends LoadCacheTask<WeatherTO> {

		public WeatherCacheLoader(Context context, String cacheKey, Class<WeatherTO> clazz) {
			super(context, cacheKey, clazz);
		}

		@Override
		protected void onPostExecute(Cache<WeatherTO> result) {
			super.onPostExecute(result);
			if (result != null) {
				mWeatherTO = result.getData();
				mWeatherView.setImageResource(getWeatherImage(mContext, mWeatherTO.getWeatherCode()));
			}
			new RequestWeatherTask().execute();
		}
	}

	class RequestWeatherTask extends AsyncTask<Void, Void, BDLocation> {
		private CountDownLatch mLatch = new CountDownLatch(1);

		@Override
		protected BDLocation doInBackground(Void... params) {
			BDLocation location = YBApp.get().getLocation();
			try {
				int waitCount = 0;
				while (location == null) {
					mLatch.await(1, TimeUnit.SECONDS);
					location = YBApp.get().getLocation();
					// 10秒后无结果直接返回
					if (waitCount >= 10) {
						break;
					}
					waitCount++;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return location;
		}

		@Override
		protected void onPostExecute(BDLocation result) {
			super.onPostExecute(result);
			requestWeather(result);
		}
	}

	private void requestWeather(BDLocation location) {
		String url = null;
		if (location == null) {
			url = UriHelper.getIPWeatherUrl();
		} else {
			url = UriHelper.getLocationWeatherUrl(location.getLatitude(), location.getLongitude());
		}
		StringRequest request = new StringRequest(url, new Listener<String>() {

			@Override
			public void onResponse(String response) {
				parseWeather(response);
			}
		}, new ErrorListener() {

			@Override
			public void onErrorResponse(VolleyError error) {

			}
		});
		RequestManager.startVolleyRequest(mContext, request);
	}

	private synchronized void parseWeather(String result) {
		WeatherTO weatherTO = null;
		try {
			JSONObject jsonObject = new JSONObject(result);
			JSONArray weatherList = jsonObject.getJSONArray("weather");
			JSONObject weatherObj = weatherList.getJSONObject(0);
			String cityName = weatherObj.getString("city_name");
			JSONObject nowJSON = weatherObj.getJSONObject("now");
			String weatherText = nowJSON.getString("text");
			String weatherCode = nowJSON.getString("code");
			String windDirection = nowJSON.getString("wind_direction");
			String windScale = nowJSON.getString("wind_scale");
			String humidity = nowJSON.getString("humidity");
			String pressure = nowJSON.getString("pressure");
			JSONArray featureList = weatherObj.getJSONArray("future");
			String highTemp = null;
			String lowTemp = null;
			if (featureList.length() > 0) {
				JSONObject featureObject = featureList.getJSONObject(0);
				highTemp = featureObject.getString("high");
				lowTemp = featureObject.getString("low");
			}
			weatherTO = new WeatherTO();
			weatherTO.setCityName(cityName);
			weatherTO.setHighTemp(highTemp);
			weatherTO.setHumidity(humidity);
			weatherTO.setLowTemp(lowTemp);
			weatherTO.setPressure(pressure);
			weatherTO.setWeatherCode(weatherCode);
			weatherTO.setWeatherText(weatherText);
			weatherTO.setWindDirection(windDirection);
			weatherTO.setWindScale(windScale);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		if (weatherTO != null) {
			mWeatherTO = weatherTO;
			if (mPopup != null && mPopup.isShowing()) {
				mPopup.setWeather(mWeatherTO);
			}
			mWeatherView.setImageResource(getWeatherImage(mContext, weatherTO.getWeatherCode()));
			CacheDao.addOrUpdateCache(mContext, CACHE_KEY_WEATHER, weatherTO);
		}
	}

	public int getWeatherImage(Context context, String weatherCode) {
		return context.getResources().getIdentifier("w" + weatherCode, "drawable", context.getPackageName());
	}

}
